package com.atguigu.bookcity.entity.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.bookcity.exception.BookCityException;
import com.atguigu.bookcity.entity.Book;
import com.atguigu.bookcity.service.BookService;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

@AllArgsConstructor
@NoArgsConstructor
public class BookExcelListener extends AnalysisEventListener<ExcelBook> {

    private BookService bookService;
    private static final int MAX_COUNT = 1000;
    private final List<Book> list = new ArrayList<>();

    @Override
    public void invoke(ExcelBook excelBook, AnalysisContext analysisContext) {
        if (excelBook == null)
            throw new BookCityException(500, "Excel中无数据");
        Book book = new Book();
        BeanUtils.copyProperties(excelBook, book);
        list.add(book);
        if (list.size() > MAX_COUNT) {
            bookService.saveBatch(list);
            list.clear();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        bookService.saveBatch(list);
    }
}
